﻿using Microsoft.Xna.Framework.Audio;

namespace TrinityEngine
{
    public class AudioSource : Component
    {
        public SoundEffect clip
        {
            get { return _clip; }
            set
            {
                _clip = value;
                _sound = _clip.CreateInstance();
            }
        }
        private SoundEffect _clip;
        private SoundEffectInstance _sound;

        public bool isPlaying { get; private set; }

        public bool isLooped
        {
            get { return _sound.IsLooped; }
            set { _sound.IsLooped = value; }
        }

        public float volume
        {
            get { return _sound.Volume; }
            set { _sound.Volume = value; }
        }

        public float pan
        {
            get { return _sound.Pan; }
            set { _sound.Pan = value; }
        }

        public float pitch
        {
            get { return _sound.Pitch; }
            set { _sound.Pitch = value; }
        }

        public AudioSource(SoundEffect clip)
        {
            this.clip = clip;
            isLooped = false;
            pan = 0f;
            volume = 1f;
            pitch = 0f;
        }

        public void Play()
        {
            if (_sound == null)
            {
                return;
            }

            isPlaying = true;

            if (!enabled)
            {
                _sound.Play();
            }

        }

        public void Pause()
        {
            isPlaying = false;
            _sound.Pause();
        }

        public void Stop()
        {
            isPlaying = false;
            _sound.Stop();
        }

        protected override void OnEnable()
        {
            if (isPlaying && _sound.State == SoundState.Paused)
            {
                _sound.Play();
            }
        }

        protected override void OnDisable()
        {
            _sound.Pause();
        }

        protected override void OnDestroy()
        {
            _sound.Stop();
            _sound = null;
            _clip = null;
        }
    }
}
